package com.whc.pay.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.whc.api.dto.PayApplyDTO;
import com.whc.common.context.BaseContext;
import com.whc.common.utils.SnowflakeIdGenerator;

import com.whc.pay.domain.entity.PayOrder;
import com.whc.pay.mapper.PayOrderMapper;
import com.whc.pay.service.IPayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;



@Service
@Slf4j
public class PayOrderServiceImpl implements IPayOrderService {
    @Autowired
    private PayOrderMapper payOrderMapper;

    private final SnowflakeIdGenerator snowflakeId=new SnowflakeIdGenerator(0,0);

    @Override
    public void addPay(PayApplyDTO payApplyDTO) {

        Long userid=BaseContext.getCurrentId();
        log.info("通过theadlocal获取到userid"+userid);
        if(userid==null){
            throw new RuntimeException("用户未登录");
        }
        PayOrder payOrder = PayOrder.builder().payNumber(snowflakeId.generateId()).orderNumber(payApplyDTO.getOrderNumber()).
                buyerId(userid).amount(payApplyDTO.getAmount()).status(1)
                .createTime(LocalDateTime.now()).paySuccessTime(null)
                .isDelete(false).build();
        payOrderMapper.insert(payOrder);

    }

    @Override
    public void deletePay(long payId) {
        UpdateWrapper<PayOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",payId);
        updateWrapper.set("is_delete",true);
        payOrderMapper.update(updateWrapper);
//        payOrderMapper.deleteById(payId);
    }

    @Override
    public PayOrder selectByOrderId(long orderId) {
        QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_number",orderId);
        return payOrderMapper.selectOne(queryWrapper);
    }

    @Override
    public void toPay(long payId) {
        UpdateWrapper<PayOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",payId);
        //修改为已支付
        updateWrapper.set("status",3);
        updateWrapper.set("pay_success_time",LocalDateTime.now());


        payOrderMapper.update(updateWrapper);
    }
}
